package com.dylan.netty.nio.file;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * @author zhangshaojian
 * @date 2022/8/9 20:41
 */
@Slf4j
public class Test {
    @SneakyThrows
    public static void main(String[] args) {
//        writeContentToFile();
//        printFileContent();
        onlyReadBuffer();
    }

    private static void onlyReadBuffer() {
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        for (int i = 0; i < byteBuffer.capacity(); i++) {
            byteBuffer.put((byte) i);
        }
        ByteBuffer buffer = byteBuffer.asReadOnlyBuffer();
        byteBuffer.put(0, (byte) 4);
        byteBuffer.flip();
        while (byteBuffer.hasRemaining()) {
            System.out.println(byteBuffer.get());
        }
        System.out.println("============================");
        buffer.flip();
        while (buffer.hasRemaining()) {
            System.out.println(buffer.get());
        }
    }

    private static void writeContentToFile() {

        try (
                FileOutputStream fileOutputStream = new FileOutputStream("D:\\121.txt", true);
                FileChannel channel = fileOutputStream.getChannel()
        ) {
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            byteBuffer.put("\n新插入的内容哦！\n".getBytes(StandardCharsets.UTF_8));
            byteBuffer.put("拜了个拜！".getBytes(StandardCharsets.UTF_8));
            byteBuffer.flip();
            channel.write(byteBuffer);
        } catch (Exception ex) {
            log.error("文件写入开了个小差！！");
        }

    }

    private static void printFileContent() {
        try (
                FileInputStream fileInputStream = new FileInputStream("D:\\121.txt");
                FileChannel channel = fileInputStream.getChannel()
        ) {
            ByteBuffer byteBuffer = ByteBuffer.allocate(fileInputStream.available());
            channel.read(byteBuffer);
            byteBuffer.flip();
            byte[] array = byteBuffer.array();
            System.out.println(new String(array));
        } catch (Exception ex) {
            log.error("文件出了点小差！！！", ex);
        }
    }
}
